package com.kun.index.controller;


import com.kun.common.Constants;
import com.kun.common.ResultDto;
import com.kun.common.annotation.PermissionAuthentication;
import com.kun.common.exception.MyException;
import com.kun.index.controller.dto.LoginDto;
import com.kun.index.entity.*;
import com.kun.index.service.LabelService;
import com.kun.index.service.impl.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 博客表 前端控制器
 * </p>
 *
 * @author kunkun
 * @since 2024-02-28
 */
@RestController
@RequestMapping("/index/blog")
public class BlogController {

    @Autowired
    private BlogServiceImpl blogService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private BlogLabelServiceImpl blogLabelService;
    @Autowired
    private LabelServiceImpl labelService;
    @Autowired
    private LikeUserBlogServiceImpl likeUserBlogService;
    @Autowired
    private CollectUserBlogServiceImpl collectUserBlogService;
    @Autowired
    private CommentServiceImpl commentService;
    @Autowired
    private HistoryServiceImpl historyService;
    @Autowired
    private RateUserBlogServiceImpl rateUserBlogService;

    @GetMapping("/queryBlogById")
    @ApiOperation("通过id查询博客信息")
    @PermissionAuthentication
    public ResultDto queryBlogById(@RequestParam(name = "id", required=true)Integer id){
        Blog blog = blogService.queryBlogById(id);
        if (blog!=null){
//            注入userNickname内容
            blog.setUserNickname(userService.queryUserById(blog.getUserId()).getNickname());

//            注入labelIds内容
            List<BlogLabel> blogLabels= blogLabelService.queryByBlogId(blog.getId());
            ArrayList<Integer> labelIds = new ArrayList<>();
            for (BlogLabel blogLabel : blogLabels) {
                labelIds.add(blogLabel.getLabelId());
            }
            blog.setLabelIds(labelIds);

//            注入labels内容
            List<Label> labels= labelService.queryByLabelIds(labelIds);
            blog.setLabels(labels);

//                对每个blog注入likeCount属性
            Integer num = likeUserBlogService.queryLikeNum(blog.getId());
            blog.setLikeCount(num);

            return ResultDto.success(blog);
        }else{
            return ResultDto.fail(Constants.CODE_302,"数据查询不到,请重新查找数据");
        }


    }

    @GetMapping("/queryAllBlogs")
    @ApiOperation("查询所有的blog")
    @PermissionAuthentication
    public ResultDto queryAllBlogs(@RequestParam(name = "pageIndex", required=false)Integer pageIndex,
                                   @RequestParam(name = "pageSize", required=false)Integer pageSize,
                                   @RequestParam(name = "auditStatue", required=false)Integer auditStatue,
                                   @RequestParam(name = "queryTitleLike", required=false)String queryTitleLike,
                                   @RequestParam(name = "orderByUpdateTime", required=false)Boolean orderByUpdateTime,
                                   @RequestParam(name = "queryLabelId", required=false)Integer queryLabelId) {
        HashMap<String, Object> map = new HashMap<>();
        if (pageIndex != null) {
            map.put("pageIndex", pageIndex);
        }
        if (pageSize != null) {
            map.put("pageSize", pageSize);
        }
        if (auditStatue != null) {
            map.put("auditStatue", auditStatue);
        }
        if (queryTitleLike != null) {
            map.put("queryTitleLike", queryTitleLike);
        }
        if (orderByUpdateTime != null) {
            map.put("orderByUpdateTime", orderByUpdateTime);
        }
        if (queryTitleLike != null) {
            map.put("queryLabelId", queryLabelId);
        }
        Map<String, Object> resultMap = blogService.queryBlogs(map);
        if (((List<Blog>) resultMap.get("blogs")).size() > 0) {
            for (Blog blog : ((List<Blog>) resultMap.get("blogs"))) {
//                删减content内容，便于快速响应数据
                if (blog.getContent().length()>100){
                    blog.setContent(blog.getContent().substring(0,101));
                }
//                对每个blog注入userNickname字段
                blog.setUserNickname(userService.queryUserById(blog.getUserId()).getNickname());

//                对每个blog注入labels属性
                List<Label> list =labelService.queryByBlogId(blog.getId());
                blog.setLabels(list);

//                对每个blog注入likeCount属性
                Integer num = likeUserBlogService.queryLikeNum(blog.getId());
                blog.setLikeCount(num);

//                对每个blog注入collectionCount属性
                Integer num1 = collectUserBlogService.queryCollectionNum(blog.getId());
                blog.setCollectionCount(num1);
            }
//            筛选所有labels包含queryLabelId的对象
//            if (queryLabelId!=null){
//                Label label= labelService.queryByLabelId(queryLabelId);
//                List<Blog> blogs = ((List<Blog>) resultMap.get("blogs")).stream().filter(v -> (v.getLabels().contains( label ))).collect(Collectors.toList());
//                resultMap.put("blogs",blogs);
//            }
            return ResultDto.success(resultMap);
        } else {
            return ResultDto.fail(Constants.CODE_301, "数据为空,请重新添加数据");
        }


    }

    @PostMapping("/addBlog")
    @ApiOperation("新增博客")
    public ResultDto addBlog(@RequestBody Blog blog){
        Integer id = blogService.addBlog(blog);
        if (blog.getLabelIds()!=null){
            for (Integer labelId : blog.getLabelIds()) {
                blogLabelService.addBlogLabel(new BlogLabel(labelId,id));
            }
        }
        if (id!=null){
            return ResultDto.success("新增博客成功");
        }else{
            return ResultDto.fail("新增博客失败");
        }
    }

    @GetMapping("/addHitsNum")
    @ApiOperation("新增博客点击量")
    public ResultDto addHitsNum(@RequestParam(name = "id", required=true)Integer id){
        Integer num = blogService.addBlogHitsNum(id);
        if (num!=null){
            return ResultDto.success(num);
        }else{
            return ResultDto.fail("新增博客点击量失败");
        }
    }

    @GetMapping("/updateBlogAuditStatue")
    @ApiOperation("更新博客审核状态")
    public ResultDto updateBlogAuditStatue(@RequestParam("id") Integer blogId){
        Blog blog = blogService.queryBlogById(blogId);
        blog.setAuditStatue((blog.getAuditStatue()==1)?0:1);
        Integer num = blogService.updateBlog(blog);
        if (num>0){
            return ResultDto.success("更新成功");
        }else {
            return ResultDto.fail("更新失败");
        }
    }

    @PostMapping("/updateBlog")
    @ApiOperation("编辑博客")
    public ResultDto updateBlog(@RequestBody Blog blog){
        //1.更新博客信息
        int num = blogService.updateBlog(blog);
        //2.删除博客标签联系
        blogLabelService.deleteBlogLabelByBlogId(blog.getId());

        //3.新增博客标签联系
        for (Integer labelId : blog.getLabelIds()) {
            blogLabelService.addBlogLabel(new BlogLabel(labelId,blog.getId()));
        }

        if (num>0){
            return ResultDto.success("修改博客成功");
        }else{
            return ResultDto.fail("修改博客失败");
        }


    }

    @PostMapping("/deleteBlog")
    @ApiOperation("删除博客")
    public ResultDto deleteBlog(@RequestBody Blog blog){
        //1.删除相关的评论
        List<Comment> comments = commentService.queryCommentsByBlogId(blog.getId());
        for (Comment comment : comments) {
            commentService.deleteCommentById(comment.getId());
        }
        //2.删除相关的历史记录
        HashMap<String, Object> history_condition = new HashMap<>();
        history_condition.put("blogId",blog.getId());
        List<History> histories = (List<History>) historyService.queryHistoryByConditions(history_condition).get("histories");
        for (History history : histories) {
            historyService.deleteHistory(history);
        }

        //3.删除相关的收藏
        HashMap<String, Object> collectUserBlog_condition = new HashMap<>();
        collectUserBlog_condition.put("blogId",blog.getId());
        List<CollectUserBlog> collectUserBlogs = collectUserBlogService.queryCollectUserBlogByConditions(collectUserBlog_condition);
        for (CollectUserBlog collectUserBlog : collectUserBlogs) {
            collectUserBlogService.deleteCollection(collectUserBlog);
        }

        //4.删除相关的点赞
        HashMap<String, Object> likeUserBlog_condition = new HashMap<>();
        likeUserBlog_condition.put("blogId",blog.getId());
        List<LikeUserBlog> likeUserBlogs = likeUserBlogService.queryLikeUserBlogByConditions(likeUserBlog_condition);
        for (LikeUserBlog likeUserBlog : likeUserBlogs) {
            likeUserBlogService.deleteLike(likeUserBlog);
        }

        //5.删除相关的评分
        HashMap<String, Object> rateUserBlog_condition = new HashMap<>();
        rateUserBlog_condition.put("blogId",blog.getId());
        List<RateUserBlog> rateUserBlogs = (List<RateUserBlog>) rateUserBlogService.queryRateByCondition(rateUserBlog_condition).get("rates");
        for (RateUserBlog rateUserBlog : rateUserBlogs) {
            rateUserBlogService.deleteRate(rateUserBlog);
        }

        //6. 删除相关的BlogLabel
        blogLabelService.deleteBlogLabelByBlogId(blog.getId());

        int num = blogService.deleteBlog(blog);
        if (num>0){
            return ResultDto.success("删除博客成功");
        }else{
            return ResultDto.fail("删除博客失败");
        }


    }
    @PostMapping("/batchDeleteBlog")
    @ApiOperation("批量删除博客")
    public ResultDto batchDeleteBlog(@RequestBody List<Integer> ids){
        int num=1;
        for (Integer id : ids) {
            Blog blog = blogService.queryBlogById(id);
            this.deleteBlog(blog);
        }
        if (num>0){
            return ResultDto.success("删除博客成功");
        }else{
            return ResultDto.fail("删除博客失败");
        }


    }

    @GetMapping("/queryAllBlogsByLabelId")
    @ApiOperation("通过labelId查询所有的blog")
    public ResultDto queryAllBlogsByLabelId(@RequestParam(value = "labelId",required = false)Integer labelId) {
        //查询所属的所有blogId
        List<BlogLabel> blogLabels = blogLabelService.queryByLabelId(labelId);
        ArrayList<Integer> blogIds = new ArrayList<>();
        for (BlogLabel blogLabel : blogLabels) {
            blogIds.add(blogLabel.getBlogId());
        }

        List<Blog> blogs = blogService.queryBlogsByIds(blogIds);
        if (blogs.size() > 0) {
            for (Blog blog : blogs) {
//                删减content内容，便于快速响应数据
                if (blog.getContent().length()>100){
                    blog.setContent(blog.getContent().substring(0,101));
                }
//                对每个blog注入userNickname字段
                blog.setUserNickname(userService.queryUserById(blog.getUserId()).getNickname());
            }
            return ResultDto.success(blogs);
        } else {
            return ResultDto.fail(Constants.CODE_301, "数据为空,请重新添加数据");
        }


    }

    @PostMapping("/queryAllBlogsByIds")
    @ApiOperation("通过ids查询所有的blog")
    public ResultDto queryAllBlogsByIds(@RequestBody ArrayList<Integer> ids) {
        List<Blog> blogs = blogService.queryBlogsByIds(ids);
        if (blogs.size() > 0) {
            for (Blog blog : blogs) {
//                删减content内容，便于快速响应数据
                if (blog.getContent().length()>100){
                    blog.setContent(blog.getContent().substring(0,101));
                }
//                对每个blog注入userNickname字段
                blog.setUserNickname(userService.queryUserById(blog.getUserId()).getNickname());

//                对每个blog注入avatarUrl字段
                blog.setAvatarUrl(userService.queryUserById(blog.getUserId()).getAvatarUrl());
            }
            return ResultDto.success(blogs);
        } else {
            return ResultDto.fail(Constants.CODE_301, "数据为空,请重新添加数据");
        }


    }

}

